package server;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;

import ocsf.server.AbstractServer;
import ocsf.server.ConnectionToClient;
import client.Answers;
import client.Cart;
import client.ComplaintThread;
import client.CreditCard;
import client.Delivery;
import client.Item;
import client.Main;
import client.MemberAccount;
import client.MemberApproval;
import client.Order;
import client.SearchDetails;
import client.Subscribe;
import client.Survey;
import client.User;

/**
 * This class overrides some of the methods in the abstract 
 * superclass in order to give more functionality to the server.
 * @version July 2000
 */
public class EchoServer extends AbstractServer 
{
  //Class variables *************************************************
  
  /**
   * The default port to listen on.
   */
  final public static int DEFAULT_PORT = 5555;
  public DBcheck db = new DBcheck();
  public Threads checkUserStatus = new Threads();
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the echo server.
   *
   * @param port The port number to connect on.
   */
  public EchoServer(int port) 
  {
    super(port);
    checkUserStatus.start();
  }

  
  //Instance methods ************************************************
  
  /**
   * This method handles any messages received from the client.
   *
   * @param msg The message received from the client.
   * @param client The connection from which the message originated.
   */
public void handleMessageFromClient(Object msg, ConnectionToClient client)
  {
	  try 
	   {      	
		    java.sql.Connection conn = DriverManager.getConnection(Main.sets[0], Main.sets[1], Main.sets[2]);
		    System.out.println("SQL connection succeed");
		     
		    if(msg instanceof User)
			{	
		    	//if(((User)msg).logout == true)			//if user logging out, remove from list
					//checkUserStatus.removeClient(client);
		    	
		    	msg = (Object)msg;
				msg = db.authenticate(msg, conn);
				
				if(((User)msg).logout == false)			//if user logging in add to list
				    checkUserStatus.addClient((User)msg, client);
				
				System.out.println("instanceof User");
			}
		    if(msg instanceof Order)
			{
				if(((Order)msg).getSet.equals("get"))	
					msg = db.getOrderData(msg,conn);
				else    
					if(((Order)msg).getSet.equals("set"))
						msg = db.setOrderData(msg,conn);
				
				System.out.println("instanceof Order");
			}
		    if(msg instanceof CreditCard)
			{
				msg =(Object)msg;
				String state=((CreditCard) msg).expireMonth;
				if(state.equals("-1"))	msg = db.getSelectedCreditCard(msg,conn);
				else    msg = db.createNewCreditCard(msg,conn);
				System.out.println("instanceof CreditCard");
			}
			if(msg instanceof Item)
			{
				msg =(Object)msg;
				msg = db.updateCatalog(msg,conn);
				System.out.println("instanceof Item(updateCatalog)");
			}
		    
		    if(msg instanceof Delivery)
		    {
		    	msg=db.getMember(msg, conn);
		    	System.out.println("instanceof Delivery");
		    }
		    
		    if(msg instanceof ComplaintThread)
		    {
		    	msg=db.compThread(conn);
		    	System.out.println("instance of compalint thread");
		    }
		    
		    if(msg instanceof Subscribe)
		    {
		    	msg=db.setSubscribe(msg, conn);
		    	System.out.println("instanceof Subscribe");
		    }
		    
		    if(msg instanceof MemberApproval)
		    {
		    	if(((MemberApproval)msg).getUpdate()==1)
		    	{
		    		msg=db.setMember(msg, conn);
		    		System.out.println("SET MEMBER LIST");
		    	}
		    	else
		    	{
		    		System.out.println("GET MEMBER LIST");
		    		msg=db.getMembersList(conn);
		    	}
		    	System.out.println("instanceof MemberApproval");
		    }
			
			if(msg  instanceof SearchDetails)
			{	
				msg = (Object)msg;
				msg = db.getSearchResult(msg, conn);
				System.out.println("instanceof ArrayList<Item>");
			}
			/*
			if(msg instanceof Integer)
			{
				msg =(Object)msg;
				msg = db.checkSubscribe((Integer) msg,conn);
				System.out.println("check subscribe");
			}
			*/
			
			if(msg instanceof MemberAccount)
			{
				msg = db.createMemberAccount(msg, conn);
				System.out.println("instanceof Member Account");
			}
			
			if(msg instanceof Answers)
			{
				msg = (Object)msg;
				msg = db.createAnswers(msg, conn);
				System.out.println("instanceof Answers");
			}
			
			if(msg instanceof Cart)
			{
				if(((Cart) msg).getSet == 1)
				{
					msg = (Object)msg;
					msg = db.getUserCart(msg, conn);
				}
				else if(((Cart) msg).getSet == 2)
				{
					msg = (Object)msg;
					msg = db.setUserCart(msg, conn);
				}
				else if(((Cart) msg).getSet == 3)
				{
					msg = (Object)msg;
					msg = db.setCustomUserCart(msg, conn);
				}
				else if(((Cart) msg).getSet == 4)
				{
					msg = (Object)msg;
					msg = db.removeCustomItemFromCart(msg, conn);
				}
				else if(((Cart) msg).getSet == 5)
				{
					msg = (Object)msg;
					msg = db.getItemsInCustomItem(msg, conn);
				}
				else if(((Cart) msg).getSet == 6)
				{
					msg = (Object)msg;
					msg = db.removeItemFromCustom(msg, conn);
				}
				else if(((Cart) msg).getSet == 7)
				{
					msg = (Object)msg;
					msg = db.removeItemFromCart(msg, conn);
				}
				System.out.println("instanceof Cart");
			}
			if((boolean)msg.equals("Survey"))
			{
				msg = (Object)msg;
				msg = db.getSurveySid(conn);
				System.out.println("msg = survey Sname");
			}
			if((boolean)msg.equals("checkRead"))
			{
				msg = (Object)msg;
				msg = db.checkRead(conn);
				System.out.println("msg = check Read");
			}
			if((boolean)msg.equals("Distributed Survey Sname"))
			{
				msg = (Object)msg;
				msg = db.getSurveyDistributedSid(conn);
				System.out.println("msg =distributed survey Sname");
			}
			if(msg instanceof Survey)
			{
				msg=(Survey)msg;
				if(((Survey) msg).getAnalyze()!=null)
				{
					msg = db.saveAnalyze(msg,conn);
					System.out.println("msg = survey analyze");
				}
				else System.out.println("survey analyze exist in DB");
			}
			if(msg.equals("get frozen accounts"))
			{
				msg = (Object) msg;
				String sn = "get frozen accounts";
				msg = db.getUserDetails(sn, conn);
				System.out.println("msg = frozen accounts");
			}
			if(msg instanceof String[])
			{
				String sn[];
				sn= (String[])msg;

				if(sn[0].equals("chargeBalance"))
				{
					msg = (Object)msg;
					float aInt = Float.parseFloat(sn[1]);
				//	msg = db.chargeBalance(aInt,conn);
					System.out.println("msg = chargeBalance");
				}

				if(sn[0].equals("getUpdatedCreditCardNumbers"))
				{
					msg = (Object)msg;
					int aInt = Integer.parseInt(sn[1]);
					msg = db.getUpdatedCreditCardNumbers(aInt,conn);
					System.out.println("msg = get credit nums");
				}
				if(sn[0].equals("Display Answers"))
				{
					msg = (Object)msg;
					int aInt = Integer.parseInt(sn[1]);
					msg = db.getSurveyAnswers(aInt,conn);
					System.out.println("msg = survey Answers");
				}

				if(sn[0].equals("Get Distribute"))
				{
					msg = (Object)msg;
					int sInt = Integer.parseInt(sn[1]);
					msg = db.getDistribute(sInt,conn);
					System.out.println("msg = survey get distribute value  "+msg);
				}
				if(sn[0].equals("cancelCheck"))
				{
					msg = (Object)msg;
					int sInt = Integer.parseInt(sn[1]);
					msg = db.cancelCheck(sInt,conn);
					System.out.println("msg = Cancel Order  ");
				}
				if(sn[0].equals("removeOrder"))
				{
					msg = (Object)msg;
					int sInt = Integer.parseInt(sn[1]);
					msg = db.removeOrder(sInt,conn);
					System.out.println("msg = remove Order  ");
				}
				if(sn[0].equals("Check Subscribe"))
				{
					msg =(Object)msg;
					int sInt = Integer.parseInt(sn[1]);
					msg = db.checkSubscribe(sInt,conn);
					System.out.println("check subscribe");
				}
				if(sn[0].equals("Distribute Survey"))
				{
					msg = (Object)msg;
					int sInt = Integer.parseInt(sn[1]);
					msg = db.DistributeSurvey(sInt,conn);
					System.out.println("msg = disribute survey");
				}
				if(sn[0].equals("readSurvey"))
				{
					System.out.println("start msg = read Survey");
					msg = (Object)msg;
					String split[]=new String[2];
					//String str=sn[1];
					split=sn[1].split("_");
					sn[1]=split[1];
					int sInt = Integer.parseInt(sn[1]);
					msg = db.readSurvey(sInt,conn);
					System.out.println("msg = read Survey");
				}
				else if(sn[0].equals("get complaints"))
				{
					msg = (Object)msg;
					msg = db.getComplaintDetails(sn[1],conn);
					System.out.println("msg = complaint Details" );
				}
				else if(sn[0].equals("Display Survey"))
				{
					msg = (Object)msg;
					msg = db.getSurvey(sn[1],conn);
					System.out.println("msg = survey display");
				}
				else if(sn[0].equals("get my complaints"))
				{
					msg = (Object)msg;
					msg = db.getMyComplaints(sn[1],sn[2],conn);
					System.out.println("msg = complaint user Details");
				}
				else if(sn[0].equals("Complaint Response"))
				{
					msg = (Object)msg;
					int a=db.setResponse(sn[1],sn[2],conn);
					if(a==0)
						System.out.println("msg = response added");
					else
						System.out.println("msg = response removed");
				}
				else if(sn[0].equals("Set Complaint"))
				{
					msg = db.setComplaint(sn[1],sn[2],conn);
					System.out.println("msg = complaint added");
				}
				else if(sn[0].equals("get user details"))
				{
					msg = (Object)msg;
					msg = db.getUserDetails(sn[1],conn);
					System.out.println("msg = user details");
				}
				if(sn[0].equals("change frozen details"))
				{
					db.setUserFrozen(sn[1],sn[2],conn);
				}
				if(sn[0].equalsIgnoreCase("get user priv"))
				{
					msg = (Object)msg;
					msg = db.getUserPriv(sn[1], conn);
					System.out.println("msg = user priv");
				}
				if(sn[0].equals("change user priv"))
				{
					db.changeUserPriv(sn[1],sn[2],conn);
				}
				if(sn[0].equals("costumer complaint report"))
				{
					msg = (Object)msg;
					msg = db.getCostumerComplaintReport(sn[1], sn[2], sn[3], conn);
					System.out.println("msg = costumer complaint report");
				}
				if(sn[0].equals("set balance"))
				{
					db.setCompensation(sn[1], sn[2], sn[3], conn);
				}
				if(sn[0].equals("save costumer report" ))
				{
					db.saveReport(sn,conn);
				}
				if(sn[0].equals("get report id"))
				{
						msg = db.getReportID(sn[1],conn);
				}
				if(sn[0].equals("get satisfaction report"))
				{
					msg = db.getSatisfactionRep(conn);
				}
				if(sn[0].equals("save satisfaction report"))
				{
					db.saveReport(sn, conn);
				}
				if(sn[0].equals("inventoryRep"))
				{
					msg=db.getInventoryRep(conn);
				}
				if(sn[0].equals("mngSatRep"))
				{
					msg=db.mngSatRep(conn,sn[1]);
				}
				if(sn[0].equals("mngCompRep"))
				{
					msg=db.mngCompRep(conn);
				}
				if(sn[0].equals("save inventory report"))
				{
					db.saveReport(sn, conn);
				}
				if(sn[0].equals("quarter income report"))
				{
					msg = (Object)msg;
					msg = db.getQuarterIncomeReport(sn[1],conn);
					System.out.println("msg = quarter income report");
				}
				if(sn[0].equals("save income report"))
				{
					db.saveReport(sn, conn);
				}
				if(sn[0].equals("mngInvRep"))
				{
					msg=db.mngInvRep(sn[1], conn);
				}
				if(sn[0].equals("mngQuartIncRep"))
				{
					msg=db.mngQuartIncRep(sn[1], conn);
				}
				if(sn[0].equals("get order report"))
				{
					msg = db.getOrderReport(sn[1],conn);
				}
				if(sn[0].equals("save order report"))
				{
					db.saveReport(sn,conn);
				}
				if(sn[0].equals("mngOrdRep"))
				{
					msg=db.mngOrdRep(sn[1], conn);
				}
				if(sn[0].equals("checkSub"))
					msg=db.checkSub(conn,sn[1]);
				if(sn[0].equals("set delivery"))
				{
					db.setDeliveryDetails(sn,conn);
				}
			}
				
	   }
	  	catch (SQLException ex) 
	   	{
		     System.out.println("SQLException: " + ex.getMessage());
		     System.out.println("SQLState: " + ex.getSQLState());
		     System.out.println("VendorError: " + ex.getErrorCode());
	    }
	  	try {client.sendToClient(msg);}
	  	catch (IOException e) {e.printStackTrace();}
  }

    
  /**
   * This method overrides the one in the superclass.  Called
   * when the server starts listening for connections.
   */
  protected void serverStarted()
  {
    System.out.println("Server listening for connections on port " + getPort());
  }
  
  /**
   * This method overrides the one in the superclass.  Called
   * when the server stops listening for connections.
   */
  protected void serverStopped()
  {
    System.out.println("Server has stopped listening for connections.");
  }
  
  //Class methods ***************************************************
  
  /**
   * This method is responsible for the creation of 
   * the server instance (there is no UI in this phase).
   *
   * @param args[0] The port number to listen on.  Defaults to 5555 
   *          if no argument is entered.
   */
  public static void main(String[] args) 
  {
    int port = 0; //Port to listen on
    try 
	{
		Class.forName("com.mysql.jdbc.Driver").newInstance();
	} 
    catch (Exception ex) {/* handle the error*/}
    
    try
    {
      port = Integer.parseInt(args[0]); //Get port from command line
    }
    catch(Throwable t)
    {
      port = DEFAULT_PORT; //Set port to 5555
    }
	
    EchoServer sv = new EchoServer(port);
    
    try 
    {
      sv.listen(); //Start listening for connections
    } 
    catch (Exception ex) 
    {
      System.out.println("ERROR - Could not listen for clients!");
    }
  }
}
//End of EchoServer class
